<?php
/**
 * Created by PhpStorm.
 * User: ybjaa
 * Date: 2017/5/8
 * Time: 11:15
 */

namespace App\Business\Menu;


use App\Business\BusBase;
use App\Business\ReturnResult;
use App\Models\menus_manage;
use Illuminate\Support\Facades\DB;

class SortUPMenu extends BusBase
{

    public $ID;


    protected function Handle()
    {
        return $this->SortUPMenu();
    }

    public function GetBusinessName()
    {
        return "同级菜单中向上排序";
    }


    protected function SortUPMenu()
    {

        if(!$this->ID) return ReturnResult::Error(null,"参数无效");

        //开启事务
        DB::beginTransaction();

        //取节点
        $menu=menus_manage::find($this->ID);

        if(!$menu)
        {
            DB::rollBack();
            return ReturnResult::Error(null,"参数错误");
        }

        //检测上一节点
        $previousMenu=menus_manage::where("nextID",$menu->ID)->first();


        if(!$previousMenu)
        {
            DB::rollBack();
            return ReturnResult::Error(null,"已是单层节点中的最前节点");
        }

        if($menu->parentID!==$previousMenu->parentID)
        {
            DB::rollBack();
            return ReturnResult::Error(null,"参数错误");
        }

        //检测上上节点
        $ppreviousMenu=menus_manage::where("nextID",$previousMenu->ID)->first();

        if($ppreviousMenu&&$menu->parentID!==$ppreviousMenu->parentID)
        {
            DB::rollBack();
            return ReturnResult::Error(null,"参数错误");
        }

        if($ppreviousMenu)
        {
            $ppreviousMenu->nextID=$menu->ID;
            $ppreviousMenu->save();
        }


        $nextID=$menu->nextID;
        $menu->nextID=$previousMenu->ID;
        $previousMenu->nextID=$nextID;
        $menu->save();
        $previousMenu->save();

        DB::commit();

        return ReturnResult::Success();











    }


}